package com.neudu.glsb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.glsb.commons.JSONReturn;
import com.neudu.glsb.pojo.Member;
import com.neudu.glsb.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private JSONReturn jsonReturn;

    /**
     * 分页查询所有会员
     */
    @PostMapping("/get_all_member")
    public String getAllMember(@RequestBody Map<String, Object> pageInfoMap) {
        try {
            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
            Integer pageSize = (Integer) pageInfoMap.get("pageSize");

            // 校验分页参数
            if (ObjectUtils.isEmpty(pageNum) || ObjectUtils.isEmpty(pageSize)) {
                return jsonReturn.returnError("分页参数pageNum和pageSize不能为空");
            }

            PageHelper.startPage(pageNum, pageSize);
            List<Member> memberList = memberService.list();
            PageInfo<Member> pageInfoReturn = new PageInfo<>(memberList);
            return jsonReturn.returnSuccess(pageInfoReturn);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询会员列表失败：" + e.getMessage());
        }
    }

    /**
     * 条件分页查询会员（姓名、手机号模糊查询）- 修复LambdaQueryWrapper语法错误
     */
    @PostMapping("/get_member_by")
    public String getMemberByCondition(@RequestBody Map<String, Object> conditionMap) {
        try {
            Integer pageNum = (Integer) conditionMap.get("pageNum");
            Integer pageSize = (Integer) conditionMap.get("pageSize");
            String name = (String) conditionMap.get("name");
            String phone = (String) conditionMap.get("phone");

            // 校验分页参数
            if (ObjectUtils.isEmpty(pageNum) || ObjectUtils.isEmpty(pageSize)) {
                return jsonReturn.returnError("分页参数pageNum和pageSize不能为空");
            }

            PageHelper.startPage(pageNum, pageSize);
            LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();

            if (!ObjectUtils.isEmpty(name)) {
                queryWrapper.like(Member::getName, name); // 正确：字段名而非getter方法
            }
            if (!ObjectUtils.isEmpty(phone)) {
                queryWrapper.like(Member::getPhone, phone); // 正确：保持与实体类getter一致（如果实体类是getPhone则用这个，是phone则改Member::phone）
            }

            List<Member> memberList = memberService.list(queryWrapper);
            PageInfo<Member> pageInfo = new PageInfo<>(memberList);
            return jsonReturn.returnSuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("条件查询会员失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询会员 - 修复ID类型（统一为Integer）
     */
    @PostMapping("/getmemberby_id")
    public String getMemberById(@RequestBody Map<String, Integer> idMap) { // 改为Map<String, Integer>
        try {
            Integer id = idMap.get("id"); // 接收Integer类型ID
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("会员ID不能为空");
            }
            Member member = memberService.getById(id); // 传入Integer类型ID
            return jsonReturn.returnSuccess(member);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询会员详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增会员
     */
    @PostMapping("/add_one_member")
    public String addOneMember(@RequestBody Member member) {
        try {
            // 校验必填参数
            if (ObjectUtils.isEmpty(member.getName()) || ObjectUtils.isEmpty(member.getPhone())) {
                return jsonReturn.returnError("会员姓名和手机号不能为空");
            }
            // 初始值默认处理
            if (ObjectUtils.isEmpty(member.getBalance())) {
                member.setBalance(BigDecimal.ZERO);
            }
            if (ObjectUtils.isEmpty(member.getPoints())) {
                member.setPoints(0);
            }
            boolean success = memberService.save(member);
            return success ? jsonReturn.returnSuccess("会员新增成功") : jsonReturn.returnError("会员新增失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("新增会员失败：" + e.getMessage());
        }
    }

    /**
     * 更新会员信息 - 确保ID类型一致
     */
    @PostMapping("/modify_memberby_id")
    public String modifyMemberById(@RequestBody Member member) {
        try {
            if (ObjectUtils.isEmpty(member.getId())) { // 实体类id为Integer类型
                return jsonReturn.returnError("更新失败，会员ID不能为空");
            }
            // 用getById判断是否存在（ID为Integer类型）
            Member existMember = memberService.getById(member.getId());
            if (ObjectUtils.isEmpty(existMember)) {
                return jsonReturn.returnError("更新失败，未找到对应的会员信息");
            }
            boolean success = memberService.updateById(member);
            return success ? jsonReturn.returnSuccess("会员信息更新成功") : jsonReturn.returnError("会员信息更新失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("更新会员信息失败：" + e.getMessage());
        }
    }

    /**
     * 删除会员 - 修复ID类型（统一为Integer）
     */
    @PostMapping("/remove_memberby_id")
    public String removeMemberById(@RequestBody Map<String, Integer> idMap) { // 改为Map<String, Integer>
        try {
            Integer id = idMap.get("id"); // 接收Integer类型ID
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("会员ID不能为空");
            }
            // 用getById判断是否存在
            Member existMember = memberService.getById(id);
            if (ObjectUtils.isEmpty(existMember)) {
                return jsonReturn.returnError("删除失败，未找到对应的会员信息");
            }
            boolean success = memberService.removeById(id); // 传入Integer类型ID
            return success ? jsonReturn.returnSuccess("会员删除成功") : jsonReturn.returnError("会员删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("删除会员失败：" + e.getMessage());
        }
    }

    /**
     * 会员充值 - 修复变量名错误+ID类型统一
     */
    @PostMapping("/member_recharge")
    public String memberRecharge(@RequestBody Map<String, Object> rechargeMap) {
        try {
            Integer id = (Integer) rechargeMap.get("id");
            // 关键修复：先获取字符串，再转为BigDecimal（避免Integer强转错误）
            String amountStr = rechargeMap.get("amount").toString();
            BigDecimal amount = new BigDecimal(amountStr);

            // 校验参数
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("会员ID不能为空");
            }
            if (ObjectUtils.isEmpty(amount) || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return jsonReturn.returnError("充值金额必须大于0");
            }

            Member existMember = memberService.getById(id);
            if (ObjectUtils.isEmpty(existMember)) {
                return jsonReturn.returnError("充值失败，未找到对应的会员");
            }

            boolean success = memberService.recharge(id, amount);
            return success ? jsonReturn.returnSuccess("充值成功") : jsonReturn.returnError("充值失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("会员充值失败：" + e.getMessage());
        }
    }

    /**
     * 积分兑换 - 修复ID类型（统一为Integer）
     */
    @PostMapping("/member_exchange")
    public String memberExchange(@RequestBody Map<String, Object> exchangeMap) {
        try {
            // 修复：ID类型改为Integer，与实体类一致
            Integer id = (Integer) exchangeMap.get("id");
            Integer points = (Integer) exchangeMap.get("points");

            // 校验参数
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("会员ID不能为空");
            }
            if (ObjectUtils.isEmpty(points) || points <= 0) {
                return jsonReturn.returnError("兑换积分必须大于0");
            }
            // 用getById判断会员是否存在
            Member existMember = memberService.getById(id);
            if (ObjectUtils.isEmpty(existMember)) {
                return jsonReturn.returnError("兑换失败，未找到对应的会员");
            }
            // 额外校验：积分是否充足
            if (existMember.getPoints() < points) {
                return jsonReturn.returnError("兑换失败，积分不足（当前积分：" + existMember.getPoints() + "）");
            }

            // 调用Service时传入Integer类型ID
            boolean success = memberService.exchangePoints(id, points);
            return success ? jsonReturn.returnSuccess("积分兑换成功") : jsonReturn.returnError("积分兑换失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("积分兑换失败：" + e.getMessage());
        }
    }
    @PostMapping("/get_member_by_phone")
    public String getMemberByPhone(@RequestBody Map<String, String> phoneMap) {
        try {
            String phone = phoneMap.get("phone");
            if (ObjectUtils.isEmpty(phone)) {
                return jsonReturn.returnError("手机号不能为空");
            }
            LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Member::getPhone, phone);
            Member member = memberService.getOne(queryWrapper);
            return member != null ? jsonReturn.returnSuccess(member) : jsonReturn.returnError("未查询到会员信息");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询会员失败：" + e.getMessage());
        }
    }

    /**
     * 会员消费增加积分（新增）
     */
    @PostMapping("/add_member_points")
    public String addMemberPoints(@RequestBody Map<String, Object> paramMap) {
        try {
            Integer memberId = (Integer) paramMap.get("memberId");
            BigDecimal amount = new BigDecimal(paramMap.get("amount").toString());
            if (ObjectUtils.isEmpty(memberId) || ObjectUtils.isEmpty(amount) || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return jsonReturn.returnError("参数错误");
            }
            // 1元=1积分，取整数部分
            Integer points = amount.intValue();
            boolean success = memberService.addPoints(memberId, points);
            return success ? jsonReturn.returnSuccess("积分增加成功") : jsonReturn.returnError("积分增加失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("积分操作失败：" + e.getMessage());
        }
    }
    /**
     * 退会员接口（新增）
     */
    @PostMapping("/cancel_member")
    public String cancelMember(@RequestBody Map<String, Integer> idMap) {
        try {
            Integer id = idMap.get("id");
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("会员ID不能为空");
            }

            // 校验会员是否存在且状态正常
            Member existMember = memberService.getById(id);
            if (ObjectUtils.isEmpty(existMember)) {
                return jsonReturn.returnError("退会员失败，未找到对应的会员");
            }
            if ("已注销".equals(existMember.getStatus())) {
                return jsonReturn.returnError("该会员已注销，无需重复操作");
            }

            // 执行退会员操作
            boolean success = memberService.cancelMember(id);
            return success ? jsonReturn.returnSuccess("退会员成功") : jsonReturn.returnError("退会员失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("退会员失败：" + e.getMessage());
        }
    }

}
